package com.yu.gulimall.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.yu.common.es.SkuEsModel;
import com.yu.gulimall.search.constant.EsConstant;
import com.yu.gulimall.search.service.ProductSaveService;
import org.apache.lucene.index.IndexReader;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

import static com.yu.gulimall.search.config.ElasticSearchConfig.COMMON_OPTIONS;

@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    // 引入ES客户端
    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productEsUp(List<SkuEsModel> skuEsModels) throws IOException {

        // 保存es
        // 1）建立es索引

        // 2）给es中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonStr = JSONUtil.toJsonStr(skuEsModel);
            indexRequest.source(jsonStr, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        return b;


    }
}
